<template>
  <view class="layerPublicStyle" style="padding:20px 35px 0 35px">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="terminal_type" class="_marginB" label="终端类型" v-if="user_role_type!=''">
        <uni-data-checkbox v-model="formData.terminal_type" mode="button" :localdata="formOptions.terminal_type_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item class="_marginB" label="账户余额" >
        <div class="_flex alignItems">
            <div class="_money_style">{{ userWallet.available_amount }}</div> 元
        </div>
      </uni-forms-item>
        <uni-forms-item name="deposit_account_id" label="提款账户" required>
            <uni-data-picker v-model="formData.deposit_account_id" :localdata="deposit_account_localdata"></uni-data-picker>
        </uni-forms-item>
      <uni-forms-item name="withdraw_amount" label="提现金额" required>
        <uni-easyinput placeholder="提现金额最多小数点两位，单位元" type="number" v-model="formData.withdraw_amount"></uni-easyinput>
        <div class="input_tail _flex alignItems">
          本次最多可提<div class="_money_style" style="margin:0 2px">{{ userWallet.available_amount }}</div> 元
        </div>
      </uni-forms-item>
      <uni-forms-item name="verification_code" label="动态密码" required>
        <div style="width:150px">
          <uni-easyinput  
            type="text" placeholder="请输入6位数动态密码" 
            :maxlength="6" v-model="formData.verification_code" trim="both" 
          ></uni-easyinput>
        </div>
      </uni-forms-item>
      <uni-forms-item name="withdraw_remark" label="提现附言">
        <uni-easyinput type="textarea" placeholder="提现附言" v-model="formData.withdraw_remark" trim="both"></uni-easyinput>
      </uni-forms-item>
      <!-- <view class="uni-button-group">
        <lay-button type="normal" @click="submit">确认提交</lay-button>
        <lay-button @click="closeAll">取消关闭</lay-button>
      </view> -->
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/food-withdraw-list.js';
  import {BANK_NAME_TOGGLE}  from '~@/common/bank-class.js'
  import {enumConverter}  from '../../../food-withdraw-mode/js_sdk/validator/food-withdraw-mode.js'
  import BigJs from 'big.js'
  import {checkMoneyAmount} from '~@/utils/helper.js'
  import {store} from '@/uni_modules/uni-id-pages/common/store.js'
	import {
		mapState
	} from 'vuex'

  const excludeFieds=[`operator_id`]
  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'food-withdraw-list';

  function getValidator(fields) {
    let result = {}
    fields=fields.filter(it=>{
      return !excludeFieds.includes(it)
    })
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    props:{
      callback:{
        default:()=>{},
        type:Function
      }
    },
    computed: {
			...mapState('user', ['userWallet']),
		},
    data() {
      let formData = {
        "merchant_id": "",
        "user_id": store.userInfo._id,
        "operator_id": "",
        "deposit_account_id": "",
        "withdraw_amount": null,
        "withdraw_remark": "",
        "operator_remark": "",
        "withdraw_status": 0,
        "terminal_type": 0,
        verification_code:``,
        "last_update_date": null
      }
      return {
        deposit_account_localdata:[],
        user_role_type:``,


        formData,
        formOptions: {
          "terminal_type_localdata": [
            {
              "value": 0,
              "text": "商户",
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    watch:{
      'formData.user_id':{
        handler(value){
          this.getLocaldata(value);
          getApp().updateHeaderWallet()
        },
        immediate:true
      },
    },
    mounted() {
      this.$refs.form.setRules(this.rules)
      this.callback([
            this.parentCallVerify
        ]);
    },
    methods: {
      closeAll(){
        this.$emit(`manualClose`,`addComponent`)
      },
      BigJs(args){
        return new BigJs(args)
      },
      async getLocaldata(userId){
        const {result:{ data }}=await db.collection(`food-withdraw-mode`)
        .where({
          user_id:userId,
          enable_status:true
        })
        .field(`pay_mode,bank_account_name,bank_terminal_name,bank_number`)
        .get()
        this.deposit_account_localdata=data.map(it=>{
          let selectText=`${ enumConverter.pay_mode_valuetotext[it.pay_mode] }`
          if(it.pay_mode==1){
            selectText=`${ enumConverter.pay_mode_valuetotext[it.pay_mode] } -  ${it.bank_account_name} - ${it.bank_number}`
          }
          return {
            text:selectText,
            value:it._id
          }
        })

      },
      parentCallVerify(){
        return new Promise(async resolve=>{
          const results= await this.submit();
          if(results.res!=null){
            return resolve(1)
          }
        })
    },

      /**
       * 验证表单并提交
       */
      submit() {
        return new Promise(resolve=>{
          uni.showLoading({
            mask: true
          })
          this.$refs.form.validate().then((res) => {
            const { myErrCode,errMsg}=checkMoneyAmount(res.withdraw_amount);
            if(myErrCode!==0){
              return layer.msg(errMsg, { icon : 2, time: 1500})
            }
            res.user_id=store.userInfo._id;
            res.operator_remark=``
            return this.submitForm(res)
          }).then((res)=>{
            resolve({status:`success`,res})
          }).catch((err) => {
          }).finally(() => {
            uni.hideLoading()
          })
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '发起成功'
          })
          getApp().updateHeaderWallet();
          return res
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
